package com.party.web.web.controller.crowdfundMultiple;

import com.google.common.base.Strings;
import com.party.common.paging.Page;
import com.party.core.model.YesNoStatus;
import com.party.core.model.activity.Activity;
import com.party.core.model.activity.ActivityDetail;
import com.party.core.model.activity.ActivityInput;
import com.party.core.model.activity.CrowfundResources;
import com.party.core.model.audio.Audio;
import com.party.core.model.city.City;
import com.party.core.model.crowdfund.CrowdfundEvent;
import com.party.core.model.crowdfund.CrowdfundEventWithMemberPartner;
import com.party.core.model.crowdfund.EventGradation;
import com.party.core.model.member.Member;
import com.party.core.model.partner.MemberPartner;
import com.party.core.service.activity.IActivityDetailService;
import com.party.core.service.activity.IActivityService;
import com.party.core.service.activity.ICrowfundResourcesService;
import com.party.core.service.activity.biz.ActivityDetailBizService;
import com.party.core.service.audio.IAudioService;
import com.party.core.service.city.ICityService;
import com.party.core.service.crowdfund.ICrowdfundEventService;
import com.party.core.service.crowdfund.IEventGradationService;
import com.party.core.service.member.IMemberGroupService;
import com.party.core.utils.MyBeanUtils;
import com.party.web.biz.crowdfundMultiple.EventMultipleBizService;
import com.party.web.utils.RealmUtils;
import com.party.web.web.annotation.ControlParam;
import com.party.web.web.annotation.DataControl;
import com.party.web.web.dto.AjaxResult;
import com.party.web.web.dto.input.common.CommonInput;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;
import java.util.Map;

/**
 * 众筹主题控制器
 * Created by wei.li
 *
 * @date 2017/4/26 0026
 * @time 14:04
 */
@Controller
@RequestMapping(value = "crowdfundMultiple/event")
public class EventMultipleController {

    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private ICrowdfundEventService crowdfundEventService;
    @Autowired
    private IActivityService activityService;
    @Autowired
    private ICityService cityService;
    @Autowired
    private ICrowfundResourcesService crowfundResourcesService;
    @Autowired
    private IActivityDetailService activityDetailService;
    @Autowired
    private ActivityDetailBizService activityDetailBizService;
    @Autowired
    private IAudioService audioService;
    @Autowired
    private IEventGradationService eventGradationService;
    @Autowired
    private EventMultipleBizService eventMultipleBizService;

    @Autowired
    private IMemberGroupService memberGroupService;

    /**
     * 众筹事件列表
     *
     * @param crowdfundEvent 众筹事件
     * @param page           分页参数
     * @return 事件列表
     */
    @RequestMapping(value = "list")
    public ModelAndView list(CrowdfundEventWithMemberPartner crowdfundEvent, Page page, CommonInput input) {
        page.setLimit(20);
        ModelAndView modelAndView = new ModelAndView("crowdfundMultiple/eventList");
        Map<String, Object> params = CommonInput.appendParams(input);
        List<String> orgIds = memberGroupService.getChildWithMy(RealmUtils.getCurrentUser().getId());
        params.put("orgIds", orgIds);
        crowdfundEvent.setIsMultiple(YesNoStatus.YES.getCode());
        List<CrowdfundEventWithMemberPartner> crowdfundEventList = crowdfundEventService.webListPage(crowdfundEvent, params, page);
        for (CrowdfundEvent event : crowdfundEventList) {
            Integer crowdfundNum = activityService.getCountByEventId(event.getId());
            event.setCrowdfundNum(crowdfundNum);
        }

        modelAndView.addObject("list", crowdfundEventList);
        modelAndView.addObject("page", page);
        modelAndView.addObject("input", input);
        modelAndView.addObject("event", crowdfundEvent);
        return modelAndView;
    }


    /**
     * 众筹事件视图
     *
     * @param id 事件编号
     * @return 众筹事件
     */
    @RequestMapping(value = "view")
    @DataControl
    public ModelAndView view(@ControlParam(table = "zc_event", column = "create_by", isRequired = false) String id) {
        ModelAndView modelAndView = new ModelAndView("crowdfundMultiple/eventView");

        City city = new City();
        city.setIsOpen(1);
        modelAndView.addObject("citys", cityService.list(city));

        List<Audio> audioList = null;
        //背景乐
        try {
            audioList = audioService.list(new Audio(null, com.party.common.constant.Constant.IS_CROWDFUNDED, null));
        } catch (Exception e) {
            logger.info("众筹主题详情页————获取背景乐列表失败", e.getMessage());
        }
        modelAndView.addObject("audioList", audioList);


        if (!Strings.isNullOrEmpty(id)) {
            CrowdfundEvent crowdfundEvent = crowdfundEventService.get(id);
            if (StringUtils.isNotEmpty(crowdfundEvent.getSupportRange())) {
                if (crowdfundEvent.getSwitchSupportRange() == 3) {
                    String[] ranges = crowdfundEvent.getSupportRange().split(",");
                    crowdfundEvent.setRangeStart(Integer.valueOf(ranges[0]));
                    crowdfundEvent.setRangeEnd(Integer.valueOf(ranges[1]));
                    crowdfundEvent.setSupportRange("");
                }
            }

            City c = cityService.get(crowdfundEvent.getCityId());
            if (c != null) {
                modelAndView.addObject("cityName", c.getName());
            }

            // 跑马灯
            List<CrowfundResources> picList = crowfundResourcesService.findByRefId(crowdfundEvent.getId(), "1");
            modelAndView.addObject("picList", picList);
            // 视频
            List<CrowfundResources> videoList = crowfundResourcesService.findByRefId(crowdfundEvent.getId(), "2");
            if (videoList.size() > 0) {
                modelAndView.addObject("video", videoList.get(0));
            }


            /** 活动详情 **/
            ActivityDetail activityDetail = activityDetailService.getByRefId(crowdfundEvent.getId());
            if (activityDetail != null) {
                activityDetailBizService.castToHTML(activityDetail);
            }
            modelAndView.addObject("activityDetail", activityDetail);
            modelAndView.addObject("event", crowdfundEvent);

            Activity activity = activityService.countForEventId(id);
            modelAndView.addObject("eventActivity", activity);

            List<EventGradation> eventGradations = eventGradationService.findByEventId(id);
            modelAndView.addObject("eventGradations", eventGradations);
        }
        return modelAndView;
    }


    /**
     * 保存众筹
     *
     * @param event 众筹事件
     * @return 保存结果
     */
    @ResponseBody
    @RequestMapping(value = "save")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult save(CrowdfundEvent event, BindingResult result, ActivityInput input,
                           ActivityDetail activityDetail, String multipleActStr) {
        // 数据验证
        if (result.hasErrors()) {
            List<ObjectError> allErros = result.getAllErrors();
            return AjaxResult.error(allErros.get(0).getDefaultMessage());
        }
        if (StringUtils.isEmpty(multipleActStr)) {
            return AjaxResult.error("多场活动数据不能为空");
        }
        try {
            eventMultipleBizService.eventSave(event, activityDetail, input, multipleActStr);
            return AjaxResult.success("众筹主题保存成功", event.getId());
        } catch (Exception e) {
            logger.error("保存多场主题活动异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("保存异常");
        }
    }

    @DataControl
    @RequestMapping("copyEvent")
    public ModelAndView copyEvent(@ControlParam(table = "zc_event", column = "create_by") String eventId) {
        ModelAndView modelAndView = new ModelAndView("crowdfundMultiple/publishZcActNew");
        if (StringUtils.isNotEmpty(eventId)) {
            CrowdfundEvent crowdfundEvent = crowdfundEventService.get(eventId);
            if (crowdfundEvent.getCheckStatus() == MemberPartner.PARTNER_TYPE_DEFAULT) {//防止前端篡改数据进行伪发布
                modelAndView.setViewName("redirect:/crowdfund/event/list.do");
                return modelAndView;
            }
            Activity activity = new Activity();
            try {
                MyBeanUtils.copyBeanNotNull2Bean(crowdfundEvent, activity);
            } catch (Exception e) {
                e.printStackTrace();
            }
            activity.setId(null);
            activity.setEventId(eventId);
            //个人众筹页状态，0:显示所属主题报名人员,1:显示该项目报名人员,2:不显示,默认显示主题报名人员
            activity.setPersonalPopularPageState(0);
            activity.setTitle(crowdfundEvent.getName());
            // 跑马灯
            List<CrowfundResources> picList = crowfundResourcesService.findByRefId(crowdfundEvent.getId(), "1");
            modelAndView.addObject("picList", picList);
            // 视频
            List<CrowfundResources> videoList = crowfundResourcesService.findByRefId(crowdfundEvent.getId(), "2");
            if (videoList.size() > 0) {
                modelAndView.addObject("video", videoList.get(0));
            }


            /** 活动详情 **/
            ActivityDetail activityDetail = activityDetailService.getByRefId(crowdfundEvent.getId());
            if (activityDetail != null) {
                activityDetailBizService.castToHTML(activityDetail);
            }
            modelAndView.addObject("activityDetail", activityDetail);
            modelAndView.addObject("activity", activity);

            String address = activityService.getShowAddress(activity);
            modelAndView.addObject("address", address);

            modelAndView.addObject("crowdfundEvent", crowdfundEvent);

            List<EventGradation> eventGradations = eventGradationService.withCityNameByEventId(eventId);
            modelAndView.addObject("eventGradations", eventGradations);

        } else {
            String memberId = RealmUtils.getCurrentUser().getId();
            CrowdfundEvent query = new CrowdfundEvent();
            query.setCreateBy(memberId);
            query.setProgress(YesNoStatus.YES.getCode()); // 进行中
            List<CrowdfundEvent> events = crowdfundEventService.list(query);
            modelAndView.addObject("crowdfundEventList", events);
        }
        return modelAndView;
    }
}
